package besta.moon.command;

import besta.moon.engine.selector.result.TableResult;
import besta.moon.sql.Expression;
import besta.moon.MoonConnection;
import besta.moon.statement.MoonStatement;
import besta.moon.MoonLogger;
import besta.moon.engine.selector.DataSource;
import besta.moon.sql.expression.ExpressionName;
import besta.moon.sql.expression.Expressions;
import besta.moon.sql.parser.SQLTokenizer;

public class CommandUpdate extends CommandSelect {

    private final Expressions sources = new Expressions();

    private Expression[] newRowSources;

    public CommandUpdate(MoonLogger log) {
        super(log);
    }

    public void addSetting(Expression dest, Expression source) {
        columnExpressions.add(dest);
        sources.add(source);
    }

    @Override
    public void executeImpl(MoonConnection con, MoonStatement st) throws Exception {
        int count = columnExpressions.size();
        columnExpressions.addAll(sources);
        compile(con);
        columnExpressions.setSize(count);
        newRowSources = sources.toArray();
        updateCount = 0;
        from.execute();

        for (int i = 0; i < columnExpressions.size(); i++) {
            ExpressionName expr = (ExpressionName) columnExpressions.get(i);
            DataSource ds = expr.getDataSource();
            TableResult tableResult = (TableResult) ds;
            tableResult.lock = SQLTokenizer.UPDATE;
        }

        while (true) {
            synchronized (con.getMonitor()) {
                if (!next()) {
                    return;
                }
                updateRow(con, newRowSources);
            }
            updateCount++;
        }
    }
}
